package com.ch.web.controller;

import com.ch.web.constant.FileConstant;
import com.ch.web.entity.user.XyTalkImagesEntity;
import com.ch.web.service.XyTalkImagesService;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * @author chenHao
 * @email 1429542285@qq.com
 * @date 2022-10-16 12:30:38
 */
@MultipartConfig
@RestController
@RequestMapping("xy/talkImages")
public class XyTalkImagesController {
    @Autowired
    private XyTalkImagesService xyTalkImagesService;

    /**
     * 列表
     */
    @RequestMapping("/list")

    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = xyTalkImagesService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{talkId}")

    public R info(@PathVariable("talkId") Long talkId) {
        XyTalkImagesEntity xyTalkImages = xyTalkImagesService.getById(talkId);

        return R.ok().put("xyTalkImages", xyTalkImages);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")

    public R save(@RequestBody XyTalkImagesEntity xyTalkImages) {
        xyTalkImagesService.save(xyTalkImages);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")

    public R update(@RequestBody XyTalkImagesEntity xyTalkImages) {
        xyTalkImagesService.updateById(xyTalkImages);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")

    public R delete(@RequestBody Long[] talkIds) {
        xyTalkImagesService.removeByIds(Arrays.asList(talkIds));

        return R.ok();
    }

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadTalkImage")
    public R uploadTalkImage(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(FileConstant.FILE_UPLOAD + fileName);
        while (true) {
            if (file.exists()) {
                fileName = FileConstant.doWithFileName(Objects.requireNonNull(fileName));
                file = new File(FileConstant.FILE_UPLOAD + fileName);
                continue;
            }
            multipartFile.transferTo(file);
            break;
        }
        return R.ok().put("talkUrls", FileConstant.FILE_UPLOAD_URL_PREV + fileName);
    }
}
